<template>
  <el-dialog title="员工导入" :visible="value" @close="close">
    <div class="box">
      <i class="el-icon-upload" style="font-size: 50px;color: #ccc" />
      <el-button size="mini" type="primary" @click="handleDonload">下载模板</el-button>
      <!-- 文件上传 -->
      <!--原生标签文件选择框=>打开系统文件选择文件-->
      <!--  accept原生属性直接决定文件类型
         原生事件
         change文件选择框的值变化时（选择文件）触发
    -->
      <el-button type="text" @click="$refs.file.click()">点击上传</el-button>
      <input ref="file" type="file" accept=".xlsx,.xls" style="display: none" @change="handleInput">
    </div>
    <template #footer>
      <el-button size="mini" type="primary" @click="close">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getTemplateData, uploadExcel } from '@/api/employee'
import fileSaver from 'file-saver'
export default {
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    async handleInput(e) {
      if (e.target.files.length > 0) {
        // console.log(e.target.files[0])
        // this.$emit('input', false)
        // this.$emit('success', e.target.files[0])
        try {
          await uploadExcel(e.target.files[0])
          // 提示
          this.$message.success('导入成功')
          // 关闭
          this.close()
          // 重新渲染
          this.$emit('refresh')
          // 清空文件选择框
          // this.$refs.file.value = ''
        } catch {
          // this.$refs.file.value = ''
        } finally {
          this.$refs.file.value = ''
        }
      }
    },
    close() {
      this.$emit('input', false)
    },
    async handleDonload() {
      const res = await getTemplateData()
      fileSaver.saveAs(res, '员工模板.xlsx')
    }
  }

}
</script>

<style lang="sass" scoped>
.box
  display: flex
  flex-direction: column
  width: 360px
  height: 180px
  border: 2px dashed #ccc
  justify-content: center
  border-radius: 10px
  margin: 0 auto
  align-items: center

</style>
